package com.gyh.stlserver.job;

import cn.hutool.core.util.ObjectUtil;
import com.gyh.stlserver.entity.Course;
import com.gyh.stlserver.entity.Reserve;
import com.gyh.stlserver.mapper.ReserveMapper;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@DisallowConcurrentExecution
public class ChangeReserveStatus implements Job {
    @Autowired
    private ReserveMapper reserveMapper;
    /*@Scheduled(cron = "0 0 1 * * ?")*/
    public void changeReserveStatus(){
        /*
            修改预约状态 0 取消 1未签到 2上课中 3 已完课 4已签到
            1.当前时间大于课程结束时间，状态修改为3。只需要查询状态为2的
            2.当前时间大于开课时间小于结束时间 状态修改为2。只需要查找状态为1的
        */
        /*当前时间大于开课时间小于结束时间 状态修改为2。只需要查找状态为4的*/
        Date now = new Date();
        List<Reserve> reserves1 = reserveMapper.selectReservesStatus(4);
        if (ObjectUtil.isNotEmpty(reserves1)){
            for (Reserve reserve : reserves1) {
                Course course = reserve.getCourse();
                Date courseTime = course.getTime();
                Date endTime = new Date(courseTime.getTime() + course.getLength() * 60 * 1000);
                if (now.after(courseTime)&&now.before(endTime)){
                    reserve.setStatus(2);
                    reserveMapper.update(reserve);
                }
            }
        }
        /*当前时间大于课程结束时间，状态修改为3。只需要查询状态为2的*/
        List<Reserve> reserves2 = reserveMapper.selectReservesStatus(2);
        if (ObjectUtil.isNotEmpty(reserves2)){
            for (Reserve reserve : reserves2) {
                Course course = reserve.getCourse();
                Date courseTime = course.getTime();
                Date endTime = new Date(courseTime.getTime() + course.getLength() * 60 * 1000);
                if (now.after(endTime)){
                    reserve.setStatus(3);
                    reserveMapper.update(reserve);
                }
            }
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        changeReserveStatus();
    }
}
